package com.yaser.beans;

import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.yaser.alfresco.AlfrescoWebScripts;
import com.yaser.alfresco.model.AlfrescoFolder;
import com.yaser.model.User;
import com.yaser.service.AuthenticationService;
import com.yaser.service.UserService;
import com.yaser.util.AlfrescoUtil;
import com.yaser.util.Messenger;
import com.yaser.util.exceptions.FreeBoxServiceException;
import com.yaser.util.exceptions.FreeBoxUIException;



//@ManagedBean(name="loginBean")
//@SessionScoped

@Component
@Scope("session")
@Qualifier("loginBean")
public class LoginBean {

	private User user=new User();
	
	
	@Autowired
	private AuthenticationService authenticationService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private AlfrescoWebScripts alfrescoWebScripts;
	
	@Autowired
	private Messenger messenger;
	
	public String loginUser() throws FreeBoxServiceException {
		User loginUser = authenticationService.loginUser(user.getUserName(), user.getPassword());
		if(loginUser!=null){
			try {
				loginUser.setAlf_ticket(getAlfTciket());
			} catch (FreeBoxUIException e) {
				clearUser();
				messenger.facesInfoMsg("Login failed", "Something wrong with document store");
				return "";
			}
			user = loginUser;
			return "home?faces-redirect=true";
		}else{
			clearUser();
			messenger.facesInfoMsg("Login failed", "Please check your username and password");
			return "";
		}
	}
	
	@Transactional
	public String registerUser() {
		
		if(checkUserName()){
			clearUser();
			messenger.facesInfoMsg("Registration failed", "Username exists");
			return "";
		}
		
		AlfrescoFolder folder;
		try {
			user.setAlf_ticket(getAlfTciket());
			folder = alfrescoWebScripts.createUserFolder(user.getAlf_ticket(), user.getUserName()+user.getLastName());
			user.setBaseFolderNodeRef(folder.getFolderId());
			user = userService.saveUser(user);
			return "home?faces-redirect=true";
		} catch (Exception e) {
			clearUser();
			messenger.facesErrorMsg("Registration failed", "Please try again later");
			e.printStackTrace();
		}
		
		return "";
	}

	private boolean checkUserName() {
		User loginUser = null;
		try {
			loginUser = authenticationService.loginUser(user.getUserName(), user.getPassword());
			if(loginUser!=null){
				return true;
			}
		} catch (FreeBoxServiceException e) {
			return false;
		}
		return false;
	}

	public String logoutUser() throws FreeBoxServiceException {
		clearUser();
		return "index?faces-redirect=true";
	}
	
	
	private void clearUser() {
		user.setAlf_ticket(null);
		user.setUserName(null);
		user.setBaseFolderNodeRef(null);
		user.setEmail(null);
		user.setId(null);
		user.setLastName(null);
		user.setPassword(null);
		user.setPicNodeId(null);
		user.setRegisterDate(null);
	}

	private String getAlfTciket() throws FreeBoxUIException {
		String responseLogin = null;
		
		try {
			Client c = Client.create();
			
			WebResource r2 = c.resource(AlfrescoUtil.BASE_URL+"/alfresco/service/api/login?u="+AlfrescoUtil.ADMIN_USER_NAME+"&pw="+AlfrescoUtil.ADMIN_PASSWORD+"");
			
			responseLogin = r2.accept(MediaType.APPLICATION_XML).get(String.class);
			
			responseLogin = responseLogin.substring(responseLogin.indexOf("<ticket>")+8, responseLogin.indexOf("</ticket>"));
		} catch (Exception e) {
			throw new FreeBoxUIException();
		}
		
		return responseLogin;
	}
	
	public void updateUser() throws FreeBoxUIException{
		try {
			userService.saveUser(user);
			messenger.facesInfoMsg("Success", "User updated successfully!");
		} catch (FreeBoxServiceException e) {
			messenger.facesInfoMsg("Fail", "User update failed. Please try again later!");
			throw new FreeBoxUIException(e.getMessage());
		}
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
